package com.nanfang51g3.ckz.ui.welcome;

import android.os.Environment;
import android.text.TextUtils;

import com.nanfang51g3.ckz.application.CkzApplication;
import com.nanfang51g3.ckz.di.ApiModule;
import com.nanfang51g3.ckz.domain.HttpResultBean;
import com.nanfang51g3.ckz.domain.HttpResultBeans;
import com.nanfang51g3.ckz.domain.NewProject;
import com.nanfang51g3.ckz.domain.PatchBean;
import com.nanfang51g3.ckz.exec.Api2Exception;
import com.nanfang51g3.ckz.http.HttpResultFunc;
import com.nanfang51g3.ckz.http.RestApi;
import com.nanfang51g3.ckz.http.SubscriberInterface;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.MD5Utils;
import com.nanfang51g3.ckz.utils.SPUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.TreeMap;

import javax.inject.Inject;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/4/13.
 */
public class WelcomePresenter implements WelcomeContract.WelcomeActionsListener {

    private final RestApi _restApi;
    private final WelcomeContract.View mView;

    @Inject
    public WelcomePresenter(RestApi restApi, WelcomeContract.View mView) {
        KLog.i("TAG", "进入了...WelcomePresenter");
        /**
         * @see ApiModule#provideRestApi(Retrofit)
         */
        this._restApi = restApi;
        KLog.i("TAG", _restApi == null ? "进入了...is null" : "进入了...not null");
        /**
         * @see WelcomePresenterModule#WelcomePresenterModule(WelcomeContract.View)
         */
        this.mView = mView;
        KLog.i("TAG", mView == null ? "进入了...is null" : "进入了...not null");
    }

    @Override
    public void isDownloadAPatch() {
        //APP本地应用版本
        final String local_app_v = (String) SPUtil.get(mView.getContext(), "version_code", "");
        //APP本地补丁版本
        final String path_version = (String) SPUtil.get(mView.getContext(), "path_version", "");
        final Boolean update_path = (Boolean) SPUtil.get(mView.getContext(), "update_path", false);
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("app_v", local_app_v);
        String sign = MD5Utils.getAccessToken(treeMap);
        KLog.i("Evd", sign + "-" + treeMap.toString());
        Observable observable = _restApi.isDownloadAPatch(local_app_v, sign);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new LogAppHttpResultFunc<PatchBean>())
                .subscribe(new SubscriberInterface<PatchBean>() {
                    @Override
                    public void _onError(String msg) {
                        KLog.i("Evd", "_onError " + msg);
                        mView.startView();
                    }

                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted ");
                        mView.startView();
                    }

                    @Override
                    public void onNext(PatchBean o) {
                        KLog.i("Evd", "onNext " + o.toString());

                        //应用版本相同,远程补丁号不为null,版本补丁不同
                        if (CkzApplication.VERSION_CODE.equals(o.getApp_v())) {
                            if (!TextUtils.isEmpty(o.getPath_v()))  //空则!true 非空则!false
                                if (!path_version.equals(o.getPath_v())) {
                                    KLog.i("Evd", "执行加载bug补丁");
                                    /**
                                     * @see WelcomeActivity#download(String, String)
                                     */
                                    mView.download(o.getFile(), o.getPath_v());
                                }


                        }

                    }
                });
    }

    @Override
    public void downloadAppAPatch(final String finaName, final String path_v) {
        KLog.i("TAG", _restApi == null ? "_restApi==null" : "_restApi!=null");
        final String local_app_v = (String) SPUtil.get(mView.getContext(), "version_code", "");
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("app_v", local_app_v);
        String sign = MD5Utils.getAccessToken(treeMap);
        KLog.i("Evd", sign + "-" + treeMap.toString());
        Call<ResponseBody> call = _restApi.downloadAppAPatch(local_app_v, sign);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                KLog.i("Evd", "onResponse");
                ResponseBody body = response.body();
                File futureStudioIconFile = new File(Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/" + finaName);
                try {
                    // todo change the file location/name according to your needs
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    try {
                        byte[] fileReader = new byte[4096];
                        long fileSize = body.contentLength();//获取长度
                        long fileSizeDownloaded = 0;
                        inputStream = body.byteStream();//获取读取流
                        outputStream = new FileOutputStream(futureStudioIconFile);
                        while (true) {
                            int read = inputStream.read(fileReader);
                            if (read == -1) {
                                break;
                            }
                            outputStream.write(fileReader, 0, read);
                            fileSizeDownloaded += read;
                            KLog.i("Evd", "file download: " + fileSizeDownloaded + " of " + fileSize);
                        }
                        //更新补丁
                        CkzApplication.mPatchManager.addPatch(futureStudioIconFile.getAbsolutePath());
                        //删除下载补丁
                        if (futureStudioIconFile.exists()) {
                            boolean result = futureStudioIconFile.delete();
                            if (!result)
                                KLog.i("Evd", futureStudioIconFile.getAbsolutePath() + " delete fail");
                        }
                        outputStream.flush();
                        SPUtil.putAndApply(mView.getContext(), "path_version", path_v);//更新补丁号
                        SPUtil.putAndApply(mView.getContext(), "update_path", true);//更新补丁号

                    } catch (IOException e) {
                        mView.startView();
                        KLog.i("Evd", "IOException 1 - " + e.toString());
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    }
                } catch (IOException e) {
                    KLog.i("Evd", "IOException 2 - " + e.toString());
                    mView.startView();
                }
                mView.startView();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                KLog.i("Evd", "onFailure");
                mView.startView();
            }
        });

    }

    @Override
    public void writeStreamLog() {

KLog.i("Evd","write");
        Observable observable =     _restApi.OPT("175");

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new LogAppHttpResultFunc<List<NewProject>>())
                .subscribe(new SubscriberInterface<List<NewProject>>() {
                    @Override
                    public void _onError(String msg) {

                        KLog.i("Evd", "_onError " + msg);
                    }

                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted ");
                    }

                    @Override
                    public void onNext(List<NewProject> o) {
                        KLog.i("Evd", "onNext ");

                    }

                });
       /* TreeMap<String, String> treeMap = new TreeMap<>();
        String time = "2016-05-12";
        treeMap.put("act", "down");
        treeMap.put("time", time);
        String sign = MD5Utils.
                getAccessToken(treeMap);
        Observable observable = _restApi.appLogException("down", time, sign);
        KLog.i("Evd", sign + "-" + treeMap.toString());
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new LogAppHttpResultFunc<String>())
                .subscribe(new SubscriberInterface<String>() {
                    @Override
                    public void _onError(String msg) {

                        KLog.i("Evd", "_onError " + msg);
                    }

                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted ");
                    }

                    @Override
                    public void onNext(String o) {
                        KLog.i("Evd", "onNext ");
                        File futureStudioIconFile = new File(Environment.getExternalStorageDirectory()
                                .getAbsolutePath() + "/exception_log.txt");
                        try {
                            if (!futureStudioIconFile.exists()) {
                                futureStudioIconFile.createNewFile();
                            }
                            byte bytes[] = new byte[4096];
                            bytes = o.getBytes();  //获取字节数字
                            int b = o.length(); //获取数据长度
                            FileOutputStream fos = new FileOutputStream(futureStudioIconFile);
                            fos.write(bytes, 0, b);//向文件中写入数据
                            fos.close();//关闭输出流
                        } catch (Exception e) {
                            e.printStackTrace();
                            KLog.i("Evd", e.toString());
                        }
                        KLog.i("Evd", futureStudioIconFile.getPath());
                    }

                });*/
    }
      abstract class HttpResultFuncs<T> implements Func1<HttpResultBeans<T>, T> {
        abstract public T call(HttpResultBeans<T> httpResult);
    }

    class LogAppHttpResultFunc<T> extends HttpResultFuncs<T> {
        @Override
        public T call(HttpResultBeans<T> httpResult) {
            KLog.i("Evd", httpResult.getMsg()  );

            return httpResult.getList();
        }
    }
}
